// 文件路径: myBigPro14/src001/services/speechRecognitionService.js
// Action: 完全替换

import { ref } from 'vue';
import { ElMessage } from 'element-plus';

const WEBSOCKET_URL = 'ws://localhost:8080/api/speech-stream';
const TARGET_SAMPLE_RATE = 16000; // 讯飞要求的采样率

const isListening = ref(false);
let ws = null;
let audioContext = null;
let mediaStream = null;
let processor = null;

// ======================= 【关键新增：音频重采样函数】 =======================
/**
 * 将音频数据从源采样率重采样到目标采样率
 * @param {Float32Array} inputData - 原始PCM音频数据
 * @param {number} fromSampleRate - 源采样率 (例如 48000)
 * @param {number} toSampleRate - 目标采样率 (例如 16000)
 * @returns {Float32Array} 重采样后的PCM数据
 */
function resampleAudio(inputData, fromSampleRate, toSampleRate) {
  if (fromSampleRate === toSampleRate) {
    return inputData;
  }
  const sampleRateRatio = fromSampleRate / toSampleRate;
  const newLength = Math.round(inputData.length / sampleRateRatio);
  const result = new Float32Array(newLength);
  let offsetResult = 0;
  let offsetBuffer = 0;
  while (offsetResult < result.length) {
    const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);
    let accum = 0, count = 0;
    for (let i = offsetBuffer; i < nextOffsetBuffer && i < inputData.length; i++) {
      accum += inputData[i];
      count++;
    }
    result[offsetResult] = accum / count;
    offsetResult++;
    offsetBuffer = nextOffsetBuffer;
  }
  return result;
}
// =========================================================================

const speechRecognitionService = {
  isSupported: !!(window.WebSocket && navigator.mediaDevices && window.AudioContext),
  isListening,

  start(onResult) {
    if (!this.isSupported) {
      ElMessage.error('抱歉，您的浏览器不支持WebSocket或Web Audio API，无法使用高级语音功能。');
      return;
    }
    if (isListening.value) return;

    ws = new WebSocket(WEBSOCKET_URL);
    isListening.value = true;

    ws.onopen = () => {
      console.log('成功连接到后端WebSocket服务');
      this.startAudioCapture(onResult);
    };

    ws.onmessage = (event) => {
      if (onResult && typeof onResult === 'function' && event.data) {
        onResult(event.data);
      }
    };

    ws.onerror = (error) => {
      console.error('WebSocket 发生错误:', error);
      ElMessage.error('与语音识别服务的连接发生错误。');
      this.stop();
    };

    ws.onclose = (event) => {
      console.log('与后端WebSocket服务断开连接', event.reason);
      if (isListening.value) {
        this.stop();
      }
    };
  },

  stop() {
    if (!isListening.value) return;
    
    if (mediaStream) {
      mediaStream.getTracks().forEach(track => track.stop());
      mediaStream = null;
    }
    if (processor) {
      processor.disconnect();
      processor = null;
    }
    if (audioContext && audioContext.state !== 'closed') {
      audioContext.close();
      audioContext = null;
    }
    if (ws && ws.readyState === WebSocket.OPEN) {
      ws.send("END");
      ws.close();
    }
    ws = null;
    isListening.value = false;
  },

  startAudioCapture(onResult) {
    navigator.mediaDevices.getUserMedia({ audio: true })
      .then(stream => {
        mediaStream = stream;
        audioContext = new (window.AudioContext || window.webkitAudioContext)();
        
        const source = audioContext.createMediaStreamSource(stream);
        const bufferSize = 4096;
        processor = audioContext.createScriptProcessor(bufferSize, 1, 1);

        processor.onaudioprocess = (e) => {
          if (!isListening.value || !ws || ws.readyState !== WebSocket.OPEN) return;

          const rawPcmData = e.inputBuffer.getChannelData(0);

          // 【关键修改】在发送前，先进行重采样，从浏览器默认采样率转到16kHz
          const resampledPcmData = resampleAudio(rawPcmData, audioContext.sampleRate, TARGET_SAMPLE_RATE);

          // 将重采样后的音频转为讯飞要求的16-bit整数格式
          const outputData = new Int16Array(resampledPcmData.length);
          for (let i = 0; i < resampledPcmData.length; i++) {
            let s = Math.max(-1, Math.min(1, resampledPcmData[i]));
            outputData[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
          }
          
          ws.send(outputData.buffer);
        };

        source.connect(processor);
        processor.connect(audioContext.destination);
      })
      .catch(error => {
        console.error('无法获取麦克风:', error);
        ElMessage.error('无法启动麦克风，请检查设备和浏览器权限。');
        this.stop();
      });
  }
};

export default speechRecognitionService;